package com.example.apidemo.sql;

import com.example.apidemo.login.bean.User;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


////数据库操作层

@Service
public class UserService {

    public UserRepository getUserRepository() {
        return userRepository;
    }

    public final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    // 添加用户
    public User addUser(User user) {
        return userRepository.save(user);
    }

    // 删除用户
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    // 更新用户
    public User updateUser(User user) {
        return userRepository.save(user);
    }

    // 根据ID查找用户
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    // 查找所有用户
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 查找所有用户
//    @PostMapping("/all2")
//    @ResponseBody
    public boolean getlogin(String name, String tel) {

        List<User> c = userRepository.findByNameNativeQuery(name, tel);


        if (c != null && c.size() > 0) {

            //打印结果数据
            for (User u : c) {
                System.out.println("数据：" + u.getName() + u.getTel());
            }
            return true;
        }

        //if (c != null)
        return false;

        //return new Result().success();

    }
}
